package com.ruoyi.generator.dao;

import com.ruoyi.common.core.dao.BaseDao;
import com.ruoyi.common.utils.ConvertUtil;
import com.ruoyi.common.utils.ValidateUtil;
import com.ruoyi.generator.domain.GenTableColumn;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 业务字段 数据层
 *
 * @author liuyj
 */
@Repository
public class GenTableColumnDao extends BaseDao<GenTableColumn,Long> {
    /**
     * 根据表名称查询列信息
     *
     * @param tableName 表名称
     * @return 列信息
     */
    public List<GenTableColumn> selectDbTableColumnsByName(String tableName){
        StringBuilder sql = new StringBuilder();
        sql.append(" select column_name columnName, (case when (is_nullable = 'no' && column_key != 'PRI') then '1' else null end) as isRequired ");
        sql.append(" , (case when column_key = 'PRI' then '1' else '0' end) as isPk, ordinal_position as sort, column_comment as columnComment ");
        sql.append(" , (case when extra = 'auto_increment' then '1' else '0' end) as isIncrement, column_type as columnType");
        sql.append(" from information_schema.columns ");
        sql.append(" where table_schema = (select database()) ");
        if (!ValidateUtil.isEmpty(tableName)) {
            sql.append(" and table_name ='"+tableName+"'");
        }
        sql.append(" order by ordinal_position ");
        return this.findBySQL(sql.toString());
    }

    /**
     * 查询业务字段列表
     *
     * @param tableId 业务字段编号
     * @return 业务字段集合
     */
    public List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId){
        String hql="from GenTableColumn where tableId="+tableId;
        hql+=" order by sort";
        return this.find(hql);
    }


    /**
     * 批量删除业务字段
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    public int deleteGenTableColumnByIds(Long[] ids){
        String hql="delete GenTableColumn where tableId in "+ ConvertUtil.toDbString(ids);
        return this.executeHql(hql);
    }
}
